package com.beyond.trace.controller;

import com.beyond.trace.domain.TraceBatch;
import com.beyond.trace.domain.TraceProduct;
import com.beyond.trace.domain.vo.ScreenBatchInfoVo;
import com.beyond.trace.service.ITraceBatchService;
import com.beyond.trace.service.ITraceProductService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 批次信息Controller
 * 
 * @author yao
 * @date 2022-03-02
 */
@RestController
@RequestMapping("/trace/batch")
@Api(value = "批次信息", tags = "批次信息")
public class TraceBatchController extends BaseController
{

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    @Autowired
    private ITraceBatchService traceBatchService;

    @Autowired
    private ITraceProductService traceProductService;

    @Value("${app.qr_url}")
    private String QrUrl;

    //@PreAuthorize("@ss.hasPermi('beyond:batch:list')")
    @GetMapping("/list")
    @ApiOperation("查询批次信息列表")
    public TableDataInfo list(TraceBatch traceBatch)
    {
        startPage();
        List<TraceBatch> list = traceBatchService.selectTraceBatchList(traceBatch);
        return getDataTable(list);
    }

    //@PreAuthorize("@ss.hasPermi('beyond:batch:query')")
    @GetMapping(value = "/query")
    @ApiOperation("查询批次信息列表不分页")
    public AjaxResult getInfoQuery(TraceBatch traceBatch)
    {
        return AjaxResult.success(traceBatchService.selectTraceBatchList(traceBatch));
    }

    //@PreAuthorize("@ss.hasPermi('beyond:batch:export')")
    @Log(title = "批次信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TraceBatch traceBatch)
    {
        List<TraceBatch> list = traceBatchService.selectTraceBatchList(traceBatch);
        ExcelUtil<TraceBatch> util = new ExcelUtil<TraceBatch>(TraceBatch.class);
        return util.exportExcel(list, "批次信息数据");
    }

    //@PreAuthorize("@ss.hasPermi('beyond:batch:query')")
    @GetMapping(value = "/{batchId}")
    @ApiOperation("查询批次信息列表")
    public AjaxResult getInfo(@PathVariable("batchId") Long batchId)
    {
        return AjaxResult.success(traceBatchService.selectTraceBatchById(batchId));
    }

    //@PreAuthorize("@ss.hasPermi('beyond:batch:add')")
    @Log(title = "批次信息", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增批次信息")
    public AjaxResult add(@RequestBody @Validated TraceBatch traceBatch)
    {
        if(StringUtils.isNotBlank(traceBatch.getBatchNo())){
            TraceBatch traceBatch1 = traceBatchService.selectTraceBatchByBatchNo(traceBatch.getBatchNo());
            if(traceBatch1 != null){
                return AjaxResult.error("产品批次号已存在，请重新输入");
            }
        }
        if(StringUtils.isBlank(traceBatch.getBatchProduct())){
            return AjaxResult.error("请选择产品");
        }else{
            return toAjax(traceBatchService.insertTraceBatch(traceBatch));
        }
    }

    //@PreAuthorize("@ss.hasPermi('beyond:batch:edit')")
    @Log(title = "批次信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改批次信息")
    public AjaxResult edit(@RequestBody TraceBatch traceBatch)
    {
        return toAjax(traceBatchService.updateTraceBatch(traceBatch));
    }

    //@PreAuthorize("@ss.hasPermi('beyond:batch:remove')")
    @Log(title = "批次信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{batchIds}")
    @ApiOperation("删除批次信息")
    public AjaxResult remove(@PathVariable Long[] batchIds)
    {
        return toAjax(traceBatchService.deleteTraceBatchByIds(batchIds));
    }

    @GetMapping("/screen/apply")
    @ApiOperation("大屏批次信息")
    public AjaxResult screenBatch(){
        List<ScreenBatchInfoVo> screen = this.traceBatchService.findScreen();
        if (CollectionUtils.isNotEmpty(screen)){
            screen.forEach(s ->{
                if (StringUtils.isNotEmpty(s.getBatchNo())){
                    try{
                        s.setQrCodeData(generateCode(s.getBatchNo()));
                    }catch (Exception e){}
                }
            });
        }
        return AjaxResult.success(screen);
    }

    @GetMapping("/group/sum")
    @ApiOperation("统计产品批次总数")
    public AjaxResult groupSum(){
        return AjaxResult.success(this.traceBatchService.count());
    }

//    @Log(title = "根据传入的数据生成二维码")
//    @GetMapping("/QRCode")
//    @ApiOperation("根据传入的数据生成二维码")
//    public AjaxResult genQRCode(@RequestParam(value = "batchNo") String batchNo)
//    {
//        String batchurl = "https://www.baidu.com/" + "?batchNo=" + batchNo;
//        BitMatrix bitMatrix = null;
//        String base64;
//        byte[] buffer;
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        try {
//            bitMatrix = new MultiFormatWriter().encode(batchurl, BarcodeFormat.QR_CODE, 320, 320);
//            BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
//            for (int x = 0; x < bitMatrix.getWidth(); x++) {
//                for (int y = 0; y < bitMatrix.getHeight(); y++) {
//                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
//                }
//            }
//            ImageIO.write(image, "png", bos);
//            buffer = bos.toByteArray();
//            base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(buffer);
//            return AjaxResult.success(base64);
//        }catch (Exception e){
//            return AjaxResult.error("生成异常");
//        }
//    }

    @Log(title = "根据传入的数据生成二维码")
    @GetMapping("/QRCode")
    @ApiOperation("根据传入的数据生成二维码")
    public AjaxResult genQRCode(@RequestParam(value = "batchNo") String batchNo)
    {
        try {
            return AjaxResult.success(generateCode(batchNo));
        }catch (Exception e){
            return AjaxResult.error("生成异常");
        }
    }

    private Map<String,Object> generateCode(String batchNo){
        TraceBatch traceBatch = traceBatchService.selectTraceBatchByBatchNo(batchNo);
        if(traceBatch == null) {
            return AjaxResult.error("查询产品出错，未查询到对应的产品");
        }
        TraceProduct traceProduct = traceProductService.selectTraceProductById(Long.parseLong(traceBatch.getBatchProduct()),null);
        if(traceProduct == null) {
            return AjaxResult.error("查询产品出错，未查询到对应的产品");
        }
        String batchurl = QrUrl+"?id=" + traceBatch.getBatchProduct() + "&batchNo=" + batchNo;
        System.out.println(batchurl);
        BitMatrix bitMatrix = null;
        String base64;
        byte[] buffer;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            isProduction(traceProduct);

            bitMatrix = new MultiFormatWriter().encode(batchurl, BarcodeFormat.QR_CODE, 400, 400);
            BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < bitMatrix.getWidth(); x++) {
                for (int y = 0; y < bitMatrix.getHeight(); y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
                }
            }
            ImageIO.write(image, "png", bos);
            buffer = bos.toByteArray();
            base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(buffer);
            Map<String,Object> printData = new HashMap<>();
            printData.put("QRCode",base64);
            printData.put("productId",traceProduct.getProductId());
            printData.put("productName",traceProduct.getProductName());
            printData.put("productSize",traceProduct.getProductSize());
            printData.put("productGuaranteePeriod",traceProduct.getProductGuaranteePeriod());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            printData.put("productHarvestTime",df.format(traceBatch.getBatchHarvestTime()));

            return printData;
        }catch (Exception e){
            return AjaxResult.error("生成异常");
        }
    }


    public void isProduction(TraceProduct traceProduct) {
        if (traceProduct.getCount() == null) {
            traceProduct.setCount(1);
        }
        traceProduct.setCount(traceProduct.getCount()+1);
        traceProductService.updateTraceProduct(traceProduct);
    }
}
